#include "Configuration.h"
#include <iostream>

using std::cout;

Configuration::Configuration()
{
}

Configuration::~Configuration()
{
}

Configuration &Configuration::GetConfiguration()
{
    static Configuration instance;
    return instance;
}

void Configuration::ReadConfiguration(const string & filename)
{
    ifstream ConfFile;
    ConfFile.open(filename);

    if (!ConfFile.is_open())
    {
        cerr << "打开文件失败: " << filename << "\n";
    }

    string line;

    while (getline(ConfFile, line))
    {
        if (line.empty() || line[0] == '#')
        {
            continue;
        }

        istringstream iss(line);

        string key;
        string values_str;

        if (getline(iss, key, ' ') && getline(iss, values_str))
        {
            istringstream values_stream(values_str);
            string value;
            set<string> value_set;

            while (values_stream >> value)
            {
                value_set.insert(value);
            }
            
            if(_configuration.find(key) != _configuration.end())
            {
                _configuration[key].insert(value_set.begin(), value_set.end());
            }
            else
            {
                _configuration[key] = value_set;
            }
        }
    }

    // //测试读取配置文件
    // for (const auto &entry : _configuration)
    // {
    //     cout << "Key: " << entry.first << " => Values: ";
    //     for (const auto &val : entry.second)
    //     {
    //         cout << val << " ";
    //     }
    //     cout << "\n";
    // }
    ConfFile.close();
}

vector<string> Configuration::ReadFilesInDirectory(const string& fonlderPath)
{
    vector<string> filePaths;

    DIR* dir = opendir(fonlderPath.c_str());

    if(!dir)
    {
        cerr << "无法打开目录: " << fonlderPath << "\n";
    }

    struct dirent* entry;

    while((entry = readdir(dir)) != nullptr)
    {
        string name = entry->d_name;
        if(name == "." || name == "..")
        {
            continue;
        }
        filePaths.push_back(fonlderPath + "/" + name);
    }

    closedir(dir);

    return filePaths;
}
